import React, { useCallback, useState, useEffect } from "react"
import { Field_FormSave, Field_name_id } from "@/components/utils/field.list"
import { FormProps } from "@/components/modal/form.modal"
import { FormRender, FormUpload } from "@whzhuke/antd"
import useForm from "antd/es/form/hooks/useForm"
import customsService from "@/services/customs.service"
import { PreviewContract } from "./preview.contract"
import { Button } from "antd"

interface Props {
  values?: any
}
export const EditCustoms: React.FC<Props & FormProps> = props => {
  const { values, onDone } = props
  const [form] = useForm<any>()
  const [templateOptions, setTemplateOptions] = useState<Array<{ label: string; value: any; file?: string }>>([])
  const [selectedTemplate, setSelectedTemplate] = useState<{ id: string; name: string; file?: string } | null>(null)
  const [showPreview, setShowPreview] = useState(false)

  useEffect(() => {
    customsService
      .list({ pageSize: 9999, pageNum: 1 })
      .then(res => {
        const list = Array.isArray(res?.data?.list) ? res.data.list : Array.isArray(res?.data) ? res.data : []
        const options = list.map((item: any) => ({
          label: item.templateName,
          value: item.templateId,
          file: item.templateFile
        }))
        setTemplateOptions(options)
      })
      .catch(() => {
        setTemplateOptions([])
      })
  }, [])

  // 处理模板选择
  const handleTemplateSelect = useCallback(
    (templateId: string) => {
      const template = templateOptions.find(t => t.value === templateId)
      if (template) {
        setSelectedTemplate({
          id: template.value,
          name: template.label,
          file: template.file
        })
      }
    },
    [templateOptions]
  )

  // 进入预览模式
  const handlePreview = useCallback(() => {
    if (selectedTemplate) {
      setShowPreview(true)
    }
  }, [selectedTemplate])

  // 返回选择模板
  const handleBack = useCallback(() => {
    setShowPreview(false)
    setSelectedTemplate(null)
  }, [])

  // 如果是编辑模式，直接显示预览
  useEffect(() => {
    if (values && values.templateId) {
      setSelectedTemplate({
        id: values.templateId,
        name: values.templateName || "模板",
        file: values.templateFile
      })
      setShowPreview(true)
    }
  }, [values])

  // 如果已进入预览模式，显示预览组件
  if (showPreview && selectedTemplate) {
    return (
      <div>
        <Button onClick={handleBack} style={{ marginBottom: 16 }}>
          返回选择模板
        </Button>
        <PreviewContract values={values} templateId={selectedTemplate.id} templateFile={selectedTemplate.file} onDone={onDone} />
      </div>
    )
  }

  // 选择模板阶段
  const onFinish = useCallback(
    (data: any) => {
      if (data.template) {
        handleTemplateSelect(data.template)
      }
    },
    [handleTemplateSelect]
  )

  return (
    <div>
      <FormRender
        form={form}
        initialValues={
          values
            ? {
                ...values,
                template: values.templateId || values.template
              }
            : {}
        }
        layout="horizontal"
        preserve={false}
        onFinish={onFinish}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ width: 600 }}
        fieldList={[
          values ? Field_name_id : undefined,
          {
            fieldType: "select",
            formItemConfig: {
              name: "template",
              label: "选择模板",
              required: true,
              rules: [{ required: true, message: "请选择模板" }]
            },
            config: {
              placeholder: "请选择模板",
              options: templateOptions,
              onChange: (value: string) => {
                handleTemplateSelect(value)
              }
            }
          },
          {
            fieldType: "diy",
            formItemConfig: {
              wrapperCol: { offset: 8, span: 16 }
            },
            component: (
              <Button type="primary" onClick={handlePreview} disabled={!selectedTemplate} style={{ width: "100%" }}>
                确定并预览
              </Button>
            )
          }
        ]}
        autoComplete="off"
      />
    </div>
  )
}
